package org.hales.util;

import io.jsonwebtoken.*;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * @author : Yanml
 * @date : 2022/10/19 15:13
 */

@Component
public class JwtUtil {

    private static String passwordSalt="lvchuang@2022,./";

    /**
     * 创建token
     *
     * @param userId  claim中为userId
     * @return token
     */
    public static String createToken(String userId) {
        return  Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setSubject(userId)
                .setIssuedAt(new Date())
                .setExpiration(DateUtils.addMinutes(new Date(),30))
                // .setClaims()  //存入用户信息？
                .signWith(SignatureAlgorithm.HS256,passwordSalt)
                .compact();
    }



    /**
     * JWT  解析token是否正确
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Claims parseToken(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(passwordSalt)
                    .parseClaimsJws(token)
                    .getBody();

            return claims;
        }
        catch (Exception ex)
        {
            return null;
        }
    }


    public static Date getExpirationDate(String token) throws ExpiredJwtException {
        Claims claims = parseToken(token);
        Date expiration = claims.getExpiration();
        return expiration;
    }

    public static void main(String[] args) {
       // String token = createToken("yml");

        Claims claims= parseToken("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyODkwMmJlMC01MDczLTQ5NDEtODQ5NS1lZGIyZWI4YWEzZDciLCJzdWIiOiJ5bWwiLCJpYXQiOjE2NjYxNzExNzIsImV4cCI6MTY2NjE3Mjk3Mn0.wOPP8DFNzCMDRIp9UWvsntb2jiUOf9CrZVbiakUxL-A");

        System.out.println(claims);
    }

}
